package com.cl.spark.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import okhttp3.*;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Primary
public class OKHttpUtil {


    private final static int READ_TIMEOUT = 60;
    private final static int CONNECT_TIMEOUT = 60;
    private final static int WRITE_TIMEOUT = 60;

    public static OkHttpClient okHttpCline() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.retryOnConnectionFailure(true);
        builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        builder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
        builder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
        builder.hostnameVerifier((hostname, session) -> true);
        return builder.build();
    }

    public static String okhttpPostString(String url, JSONObject param) {
        String res = "";
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = okHttpCline().newCall(request).execute();
            res = response.body().string();
            response.close();
        } catch (Exception e) {
            return null;
        }
        return res;
    }

    public static String okhttpGetString(String url, JSONObject param) {
        String res = "";
        String paramStr = "";
        if (param != null) {
            List<String> params = new ArrayList<>();
            param.forEach((key, value) -> params.add(key + "=" + value));
            if (!params.isEmpty()) {
                paramStr = "?" + String.join("&", params);
            }
        }
        Request request = new Request.Builder()
                .get()
                .url(url + paramStr)
                .build();
        try {
            Response response = okHttpCline().newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            return null;
        }
        return res;
    }

}
